﻿namespace Blaze.Framework.LuaExtensions.FileLoaders
{
    using System.IO;
    using Security;

    /// <summary>
    /// 基于StreamingAssets目录的Lua文件加载器。
    /// </summary>
    public class FromStreamingAssets
    {
        public FromStreamingAssets(string rootPath = null)
        {
            mRootPath = rootPath;
        }

        public byte[] ReadFile(ref string filePath)
        {
            var bytes = loadFromStreamingAssets(ref filePath);
            if (bytes == null)
                return null;
            using (var memoryStream = new MemoryStream(bytes))
            {
                using (var stream = new DecryptionStream(memoryStream))
                {
                    var ret = new byte[stream.Length];
                    stream.Read(ret, 0, ret.Length);
                    return ret;
                }
            }
        }

        private byte[] loadFromStreamingAssets(ref string filePath)
        {
            string fullPath;
            if (string.IsNullOrEmpty(mRootPath))
                fullPath = $"{filePath}.lua";
            else
                fullPath = $"{mRootPath}/{filePath}.lua";

            var ret = StreamingAssets.Load(fullPath);
            if (ret != null && ret.Length > 0)
                filePath = fullPath;

            if (string.IsNullOrEmpty(mRootPath))
                fullPath = $"{filePath}/init.lua";
            else
                fullPath = $"{mRootPath}/{filePath}/init.lua";

            ret = StreamingAssets.Load(fullPath);
            if (ret != null && ret.Length > 0)
                filePath = fullPath;
            return ret;
        }

        private readonly string mRootPath;
    }
}